package com.paper.tiger.easy.rpc.s.client.client;

import com.paper.tiger.easy.rpc.core.GeneralHandleData;
import com.paper.tiger.easy.rpc.core.RegisterServerMesage;
import com.paper.tiger.easy.rpc.core.ServerType;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * [简要描述]:
 * [详细描述]:
 *
 * @author ZouHaiBo
 * @version 1.0, 2021/5/31 11:33
 * @since JDK 1.8
 */
public class SelectService
{

    public static Map<String,RegisterServerMesage> map = new ConcurrentHashMap<>();


    public static void selectService () {

        GeneralHandleData data =  new GeneralHandleData();
        data.setType(ServerType.SELECT_REQUEST.getCode());


        Socket socket = null;
        ObjectInputStream inputStream = null;
        ObjectOutputStream outputStream = null;
        try
        {

            socket = new Socket();
            socket.connect(new InetSocketAddress("127.0.0.1",RegisterCenterConst.center_port));

            outputStream = new ObjectOutputStream(socket.getOutputStream());
            inputStream = new ObjectInputStream(socket.getInputStream());

            outputStream.writeObject(data);
            outputStream.flush();

            GeneralHandleData result = (GeneralHandleData) inputStream.readObject();

            System.out.println("-------------------从服务器读取到服务 "+result+"--------------------");
            List<RegisterServerMesage> list = result.getList();

            if (list != null && list.size() >0){

                for (RegisterServerMesage registerServerMesage : list)
                {
                    map.put(registerServerMesage.getInterfaceClass(),registerServerMesage);
                }
            }

            System.out.println(data);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        finally
        {
            try
            {
                socket.close();
                if (outputStream != null)
                outputStream.close();
                if (inputStream != null)
                inputStream.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }



    }

}
